﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Mvc.Ajax;

using Microsoft.Practices.Unity;

using ERPStore.Web.Html;
using ERPStore.Web.Routing;
using ERPStore.Web.Extensions;

using ERPStore.Extensions;

using CloudSoft.Extensions;

namespace ERPStore.Web.NewsLetters.Html
{
	public static class NewsLettersExtensions
	{
		public static string EncryptedHref(this NewsLetterHelper helper)
		{
			var encrypted = helper.GetKey("mailhtml");
			var link = helper.Url.RouteERPStoreUrl("HtmlNewsLetter", new { key = encrypted });
			link = "http://" + ERPStore.GlobalConfiguration.Configuration.Settings.DefaultUrl + link;
			return link;
		}

		//public static string LandingHref(this NewsLetterHelper helper, string uniqueLinkName, ERPStore.NewsLetters.Models.CustomerNewsLetter cnl)
		//{
		//    var encrypted = helper.GetKey(uniqueLinkName);
		//    var link = helper.Url.RouteERPStoreUrl("NewsLetters.LandingPage", new { landingLink = cnl.NewsLetter.LandingLink, key = encrypted });
		//    link = "http://" + GlobalConfiguration.Configuration.Settings.DefaultUrl + link;

		//    return link;
		//}

		public static string UnsubscribeHref(this NewsLetterHelper helper, ERPStore.NewsLetters.Models.CustomerNewsLetter cnl)
		{
			var encrypted = helper.GetKey("unsubscribe");;
			var link = helper.Url.RouteERPStoreUrl("NewsLetters.Unsubscribe", new { key = encrypted });
			link = link.FullUrl();

			return link;
		}

		public static MvcForm BeginSubscribeForm(this HtmlHelper helper, object htmlAttributes = null)
		{
			return helper.BeginRouteForm("NewsLetters.Subscribe", FormMethod.Post, htmlAttributes);
		}

		public static MvcForm BeginSubscribeForm(this AjaxHelper helper, AjaxOptions options, object routeValues = null, object htmlAttributes = null)
		{
			return helper.BeginERPStoreRouteForm("NewsLetters.Subscribe", routeValues, options, htmlAttributes);
		}

		public static string ContentSrc(this NewsLetterHelper helper, string resource)
		{
			var model = helper.ViewData.Model as ERPStore.NewsLetters.Models.CustomerNewsLetter;
			var path = string.Format("/newsletters/images/nl{0}/{1}", model.NewsLetter.Id, resource.TrimStart('/').TrimStart('\\'));
			return UrlCombine(helper.Settings.DefaultUrl, path);
		}

		public static string ContentSrc(this NewsLetterHelper helper, ERPStore.NewsLetters.Models.CustomerNewsLetter customerNewsLetter, string resource)
		{
			var path = string.Format("/newsletters/images/nl{0}/{1}", customerNewsLetter.NewsLetter.Id, resource.TrimStart('/').TrimStart('\\'));
			return UrlCombine(helper.Settings.DefaultUrl, path);
		}

		public static string ProductHref(this NewsLetterHelper helper, string productCode)
		{
			return helper.ProductHref("product:"+productCode, productCode);
		}

		public static string ProductHref(this NewsLetterHelper helper, string linkName, string productCode)
		{
			var key = helper.GetKey(linkName);
			var path = string.Format("/newsletters/ir/pd/{0}?code={1}", key, productCode);
			return UrlCombine(helper.Settings.DefaultUrl, path);
		}

		public static string ProductImageSrc(this NewsLetterHelper helper, string productCode, int width, int height)
		{
			var catalogService = ERPStore.GlobalConfiguration.Configuration.DependencyResolver.GetService<ERPStore.Services.ICatalogService>();
			var product = catalogService.GetProductByCode(productCode);
			if (product == null)
			{
				return "#";
			}
			var path = string.Format(product.DefaultImage.Url, width, height);
			return UrlCombine(helper.Settings.DefaultUrl, path);
		}

		public static string ProductImage(this NewsLetterHelper helper, string productCode, int width, int height)
		{
			return helper.ProductImage(productCode, width, height, false);
		}

		public static string ProductImage(this NewsLetterHelper helper, string productCode, int width, int height, bool embed)
		{
			var catalogService = ERPStore.GlobalConfiguration.Configuration.DependencyResolver.GetService<ERPStore.Services.ICatalogService>();
			var product = catalogService.GetProductByCode(productCode);
			if (product == null)
			{
				return "#";
			}
			var path = string.Format(product.DefaultImage.Url, width, height);
			var src = UrlCombine(helper.Settings.DefaultUrl, path);
			return string.Format("<img src=\"{0}\" alt=\"{1}\" {2}/>", src, product.Title.ToHtmlAttribute(), embed ? "rel=\"embed\"" : "");
		}

		public static string ProductCategoryHref(this NewsLetterHelper helper, string productCategoryCode)
		{
			return helper.ProductCategoryHref("category:"+productCategoryCode, productCategoryCode);
		}

		public static string ProductCategoryHref(this NewsLetterHelper helper, string linkName, string productCategoryCode)
		{
			var key = helper.GetKey(linkName);
            var path = string.Format("/newsletters/ir/productcategory/{0}?code={1}", key, productCategoryCode);
			return UrlCombine(helper.Settings.DefaultUrl, path);
		}

		public static string BrandHref(this NewsLetterHelper helper, string brandName)
		{
			return helper.BrandHref("brand:"+brandName, brandName);
		}

		public static string BrandHref(this NewsLetterHelper helper, string linkName, string brandName)
		{
			var key = helper.GetKey(linkName);
            var path = string.Format("/newsletters/ir/brand/{0}?code={1}", key, brandName);
			return UrlCombine(helper.Settings.DefaultUrl, path);
		}

		public static string OpenTagSrc(this NewsLetterHelper helper)
		{
			var key = helper.GetKey("openmail");
			var path = string.Format("/newsletters/tag/{0}/tag.gif", key);
			return UrlCombine(helper.Settings.DefaultUrl, path);
		}

		public static string RedirectHref(this NewsLetterHelper helper, string url)
		{
			return helper.RedirectHref("redirect", url);
		}

		public static string RedirectHref(this NewsLetterHelper helper, string linkName, string url)
		{
			var key = helper.GetKey(linkName);
            var b = System.Text.Encoding.UTF8.GetBytes(url);
            var encoded = Convert.ToBase64String(b);
            var path = string.Format("/newsletters/rd/{0}", encoded);
			path = path.AddParameter("key", key);
			return UrlCombine(helper.Settings.DefaultUrl, path);
		}

		//public static IEnumerable<SelectListItem> GetCampaignList(this HtmlHelper helper, int campaignId)
		//{
		//    var newsLetterService = DependencyResolver.Current.GetService<ERPStore.NewsLetters.Services.NewsLettersService>();

		//    int count = 0;
		//    var list = newsLetterService.GetCampaignList(0, int.MaxValue, out count);
		//    var result = from campaign in list
		//                 select new SelectListItem()
		//                 {
		//                     Text = campaign.Name,
		//                     Value = campaign.Id.ToString(),
		//                     Selected = campaign.Id == campaignId,
		//                 };

		//    return result;
		//}

		//public static IEnumerable<SelectListItem> GetNewsLetterList(this HtmlHelper helper, int campaignId)
		//{
		//    var newsLetterService = DependencyResolver.Current.GetService<ERPStore.NewsLetters.Services.NewsLettersService>();

		//    int count = 0;
		//    var list = newsLetterService.GetNewsLettersList(0, int.MaxValue, out count);
		//    var result = from newsLetter in list
		//                 select new SelectListItem()
		//                 {
		//                     Text = newsLetter.Title,
		//                     Value = newsLetter.Id.ToString(),
		//                     Selected = newsLetter.Id == campaignId,
		//                 };

		//    return result;
		//}


		public static string GetKey(this NewsLetterHelper helper, string linkName)
		{
			var model = helper.ViewData.Model as ERPStore.NewsLetters.Models.CustomerNewsLetter;
			if (model == null)
			{
				return string.Empty;
			}
			var trakingKey = new ERPStore.NewsLetters.Models.TrackingKey()
			{
				Email = model.Recipient.Email ?? string.Empty,
				NewsLetterId = model.Campaign.NewsLetterId,
				CampaignId = model.Campaign.Id,
				CreationDate = DateTime.Now,
				LinkName = linkName,
				EmailRecipientId = model.Recipient.Id,
			};

			var encryptedKey = helper.CryptoService.Encrypt(trakingKey);

			return encryptedKey;
		}

		public static string UrlCombine(string start, string end)
		{
			return string.Format("http://{0}/{1}", start.TrimEnd('/') , end.TrimStart('/'));
		}

		public static string GetFullName(this ERPStore.Models.User user)
		{
			var presentationName = user.Presentation.GetLocalizedName();
			if (!user.LastName.IsNullOrTrimmedEmpty() 
				&& !user.FirstName.IsNullOrTrimmedEmpty())
			{
				return string.Format("{0} {1} {2}", presentationName, user.FirstName.Trim(), user.LastName.Trim());
			}
			else if (!user.LastName.IsNullOrTrimmedEmpty())
			{
				return string.Format("{0} {1}", presentationName, user.LastName.Trim());
			}
			else if (user.LastName.IsNullOrTrimmedEmpty() 
				&& user.FirstName.IsNullOrTrimmedEmpty())
			{
				return "A COMPLETER";
			}
			return string.Empty; 
		}

		public static ERPStore.Models.Product GetProductByCode(this NewsLetterHelper helper, string productCode)
		{
			var catalogService = ERPStore.GlobalConfiguration.Configuration.DependencyResolver.GetService<ERPStore.Services.ICatalogService>();

			var product = catalogService.GetProductByCode(productCode);
			if (product != null)
			{
				var offerService = ERPStore.GlobalConfiguration.Configuration.DependencyResolver.GetService<ERPStore.Services.IOffersService>();
				offerService.ApplyOffers(product, null);
			}

			return product;
		}
	}
}
